﻿//用到的命名空间 
using System;
using System.Web;
using System.Xml;


namespace msBsc.Cls
{
    //继承自IHttpModule接口 
    public class UrlHttpModule : System.Web.IHttpModule
    {
        /// <summary> 
        /// 实现接口的Init方法 
        /// </summary> 
        /// <param name="context"></param> 
        public void Init(HttpApplication context)
        {
            //建立个委托让他执行下面的ReUrl_BeginRequest事件 
            context.BeginRequest += new EventHandler(ReUrl_BeginRequest);
        }
        /// <summary> 
        /// 实现接口的Dispose方法 
        /// </summary> 
        public void Dispose()
        {
        }
        /// <summary>
        /// 验证终端是手机还是PC
        /// </summary>
        /// <param name="userAgent"></param>
        /// <returns></returns>
        private bool IsMobile(string userAgent)
        {
            if (string.IsNullOrEmpty(userAgent))
            {
                userAgent = HttpContext.Current.Request.Headers["User-Agent"];
            }
            if (string.IsNullOrEmpty(userAgent))
            {
                userAgent = HttpContext.Current.Request.UserAgent;
            }
            if (string.IsNullOrEmpty(userAgent))
            {
                return false;
            }
            if (userAgent.IndexOf("Noki") > -1 || // Nokia phones and emulators    

                     userAgent.IndexOf("Eric") > -1 || // Ericsson WAP phones and emulators    

                     userAgent.IndexOf("WapI") > -1 || // Ericsson WapIDE 2.0    

                     userAgent.IndexOf("MC21") > -1 || // Ericsson MC218    

                     userAgent.IndexOf("AUR") > -1 || // Ericsson R320    

                     userAgent.IndexOf("R380") > -1 || // Ericsson R380    

                     userAgent.IndexOf("UP.B") > -1 || // UP.Browser    

                     userAgent.IndexOf("WinW") > -1 || // WinWAP browser    

                     userAgent.IndexOf("UPG1") > -1 || // UP.SDK 4.0    

                     userAgent.IndexOf("upsi") > -1 || //another kind of UP.Browser    

                     userAgent.IndexOf("QWAP") > -1 || // unknown QWAPPER browser    

                     userAgent.IndexOf("Jigs") > -1 || // unknown JigSaw browser    

                     userAgent.IndexOf("Java") > -1 || // unknown Java based browser    

                     userAgent.IndexOf("Alca") > -1 || // unknown Alcatel-BE3 browser (UP based)    



                     userAgent.IndexOf("MITS") > -1 || // unknown Mitsubishi browser    

                     userAgent.IndexOf("MOT-") > -1 || // unknown browser (UP based)    

                     userAgent.IndexOf("My S") > -1 ||//  unknown Ericsson devkit browser      

                     userAgent.IndexOf("WAPJ") > -1 ||//Virtual WAPJAG www.wapjag.de    

                     userAgent.IndexOf("fetc") > -1 ||//fetchpage.cgi Perl script from



                     userAgent.IndexOf("ALAV") > -1 || //yet another unknown UP based browser    

                     userAgent.IndexOf("Wapa") > -1 || //another unknown browser (Web based"Wapalyzer")    

                     userAgent.IndexOf("UCWEB") > -1 || //another unknown browser (Web based"Wapalyzer")    

                     userAgent.IndexOf("BlackBerry") > -1 || //another unknown browser (Webbased "Wapalyzer")                    

                     userAgent.IndexOf("J2ME") > -1 || //another unknown browser (Web based"Wapalyzer")              

                     userAgent.IndexOf("Oper") > -1 ||

                     userAgent.IndexOf("Android") > -1 ||

                     userAgent.IndexOf("iPhone") > -1 ||
                     userAgent.IndexOf("iPod") > -1 ||
                     userAgent.IndexOf("iPad") > -1 ||

                userAgent.IndexOf("mozilla") > -1)
            {

                return true;

            }

            else
            {

                return false;

            }

        }
        private void ReUrl_BeginRequest(object sender, EventArgs e)
        {
            //HttpApplication application = (HttpApplication)sender;
            //HttpContext context = application.Context;
            //string rawurl = context.Request.RawUrl;
            //byte[] bytes = System.Web.HttpUtility.UrlDecodeToBytes(rawurl, System.Text.Encoding.Default);
            //string s = System.Text.Encoding.Default.GetString(bytes);
            //context.RewritePath(s);




            HttpContext context = ((HttpApplication)sender).Context;



            //context.Request.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            //context.Response.ContentType = "text/html";
            //Custom-----c
            //ShpMana----h
            //Dealer----d
            //Sys-----s
            string HostName = context.Request.Url.Host.ToString().ToLower(); //获取URL主机地址
            if (HostName.EndsWith(".cn")
                || HostName.EndsWith(".com")
                || HostName.EndsWith(".net")
                || HostName.EndsWith(".org"))
            {
                if (!HostName.EndsWith("dijieke.com"))
                {
                    context.RewritePath("/err404.htm");
                    return;
                }
            }

            string requestPath = context.Request.RawUrl.ToLower();
            if (requestPath.EndsWith("notify_url.aspx"))
            {
                return;
            }



            if (HostName == "m.dijieke.com" || requestPath.StartsWith("/m"))
            {
                if (requestPath.StartsWith("/m/"))
                {
                    requestPath = requestPath.Substring(2);
                }
                if (requestPath.StartsWith("/??"))
                {
                    pageResourceGet.doRequest(context);
                    //context.RemapHandler(new pageResourceGet());
                    return;
                }
                if (requestPath.EndsWith("img.jpg"))
                {
                    imgRequest.doRequest(context);
                    //context.RemapHandler(new imgResourceGet());
                    return;
                }
                //if (requestPath.EndsWith("jpg") || requestPath.EndsWith("gif") || requestPath.EndsWith("png") || requestPath.EndsWith("bmp"))
                //{
                //    imgRequest.doRequest(context);
                //    //context.RemapHandler(new imgResourceGet());
                //    return;
                //}
                if (requestPath == "/" || requestPath == "/m")
                {
                    if (!IsMobile(""))
                    {
                        if (HostName == "m.dijieke.com")
                        {
                            context.Response.Redirect(context.Request.Url.ToString().ToLower().Replace("m.dijieke.com", "www.dijieke.com"), true);
                        }
                        else
                        {
                            context.Response.Redirect("/", true);
                        }
                    }
                    else
                    {
                        context.RewritePath("/mMall/Public/mfIndex.aspx");
                    }
                    return;
                }
                if (requestPath.StartsWith("/hpage") && !string.IsNullOrEmpty(context.Request.QueryString.Get("PN")))
                {
                    context.RewritePath("/HtmPages/page_" + context.Request.QueryString.Get("PN") + ".html");
                    return;
                }
                if (requestPath.StartsWith("/dpage") && !string.IsNullOrEmpty(context.Request.QueryString.Get("PN")))
                {
                    context.RewritePath("/Custom/wfPageView.aspx?" + context.Request.QueryString.ToString());
                    return;
                }

                System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"^/m[bps]_[a-zA-Z0-9]{1,50}.htm|^/m[bps]_[a-zA-Z0-9]{1,50}/");
                r.IsMatch(requestPath);
                System.Text.RegularExpressions.Match m = r.Match(requestPath);
                if (m.Success)
                {

                    string str111 = m.Value;
                    if (str111.StartsWith("/mb_"))
                    {
                        str111 = "/mMall/Buyer/mf";
                    }
                    else if (str111.StartsWith("/mp_"))
                    {
                        str111 = "/mMall/Public/mf";
                    }
                    else if (str111.StartsWith("/ms_"))
                    {
                        str111 = "/mMall/Seller/mf";
                    }
                    else if (str111.StartsWith("/cs_"))
                    {
                        str111 = "/CustomerSys/wf";
                    }

                    if (m.Value.EndsWith("/"))
                    {
                        str111 += m.Value.Substring(4, m.Value.Length - 5) + ".aspx";
                    }
                    else
                    {
                        str111 += m.Value.Substring(4, m.Value.Length - 8) + ".aspx";
                    }
                    if (!string.IsNullOrEmpty(context.Request.QueryString.ToString()))
                    {
                        context.RewritePath(str111 + "?" + context.Request.QueryString.ToString());
                    }
                    else
                    {
                        context.RewritePath(str111);
                    }
                    //requestPath = str111 + requestPath.Substring(m.Length); 
                    //context.RewritePath(requestPath);
                }
            }
            //else if(HostName != "www.dijieke.com" &&HostName != "dijieke.com"
            else
            {
                if (requestPath.StartsWith("/??"))
                {
                    pageResourceGet.doRequest(context);
                    //context.RemapHandler(new pageResourceGet());
                    return;
                }
                if (requestPath.EndsWith("img.jpg"))
                {
                    imgRequest.doRequest(context);
                    //context.RemapHandler(new imgResourceGet());
                    return;
                }
                if (requestPath == "/")
                {
                    if (IsMobile(""))
                    {
                        if (HostName.IndexOf("dijieke") != -1)
                        {
                            context.Response.Redirect(context.Request.Url.ToString().ToLower().Replace(HostName, "m.dijieke.com"), true);
                        }
                        else
                        {
                            context.Response.Redirect("/m/", true);
                        }
                    }
                    else
                    {
                        //context.RewritePath("/HtmPages/page_00.html?rm=" + msBsc.AppLogic.Cfg.SystemSet.oSystemSet.ServerVersion);
                        context.RewritePath("/wMall/Public/wfIndex.aspx");
                    }
                    return;
                }
                if (requestPath.StartsWith("/hpage") && !string.IsNullOrEmpty(context.Request.QueryString.Get("PN")))
                {
                    context.RewritePath("/HtmPages/page_" + context.Request.QueryString.Get("PN") + ".html");
                    return;
                }
                if (requestPath.StartsWith("/dpage") && !string.IsNullOrEmpty(context.Request.QueryString.Get("PN")))
                {
                    context.RewritePath("/Custom/wfPageView.aspx?" + context.Request.QueryString.ToString());
                    return;
                }

                System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"^/[wbpshdc]{1,2}_[a-zA-Z0-9]{1,50}.htm|^/[wbpshdc]{1,2}_[a-zA-Z0-9]{1,50}/");
                r.IsMatch(requestPath);
                System.Text.RegularExpressions.Match m = r.Match(requestPath);
                if (m.Success)
                {

                    string str111 = m.Value;
                    if (IsMobile(""))
                    {
                        if (str111.StartsWith("/wb_"))
                        {
                            str111 = "/mMall/Buyer/mf";
                            if (m.Value.EndsWith("/"))
                            {
                                str111 += m.Value.Substring(4, m.Value.Length - 5) + ".aspx";
                            }
                            else
                            {
                                str111 += m.Value.Substring(4, m.Value.Length - 8) + ".aspx";
                            }
                        }
                        else if (str111.StartsWith("/wp_"))
                        {
                            str111 = "/mMall/Public/mf";
                            if (m.Value.EndsWith("/"))
                            {
                                str111 += m.Value.Substring(4, m.Value.Length - 5) + ".aspx";
                            }
                            else
                            {
                                str111 += m.Value.Substring(4, m.Value.Length - 8) + ".aspx";
                            }
                        }
                        else if (str111.StartsWith("/ws_"))
                        {
                            str111 = "/mMall/Seller/mf";
                            if (m.Value.EndsWith("/"))
                            {
                                str111 += m.Value.Substring(4, m.Value.Length - 5) + ".aspx";
                            }
                            else
                            {
                                str111 += m.Value.Substring(4, m.Value.Length - 8) + ".aspx";
                            }
                        }
                        else if (str111.StartsWith("/cs_"))
                        {
                            str111 = "/CustomerSys/wf";
                            if (m.Value.EndsWith("/"))
                            {
                                str111 += m.Value.Substring(4, m.Value.Length - 5) + ".aspx";
                            }
                            else
                            {
                                str111 += m.Value.Substring(4, m.Value.Length - 8) + ".aspx";
                            }
                        }




                        else if (str111.StartsWith("/s_"))
                        {
                            str111 = "/Sys/wf";
                            if (m.Value.EndsWith("/"))
                            {
                                str111 += m.Value.Substring(3, m.Value.Length - 4) + ".aspx";
                            }
                            else
                            {
                                str111 += m.Value.Substring(3, m.Value.Length - 7) + ".aspx";
                            }
                        }
                        else if (str111.StartsWith("/c_"))
                        {
                            str111 = "/Custom/wf";
                            if (m.Value.EndsWith("/"))
                            {
                                str111 += m.Value.Substring(3, m.Value.Length - 4) + ".aspx";
                            }
                            else
                            {
                                str111 += m.Value.Substring(3, m.Value.Length - 7) + ".aspx";
                            }
                        }
                        else if (str111.StartsWith("/h_"))
                        {
                            str111 = "/ShpMana/wf";
                            if (m.Value.EndsWith("/"))
                            {
                                str111 += m.Value.Substring(3, m.Value.Length - 4) + ".aspx";
                            }
                            else
                            {
                                str111 += m.Value.Substring(3, m.Value.Length - 7) + ".aspx";
                            }
                        }
                        else if (str111.StartsWith("/d_"))
                        {
                            str111 = "/Dealer/wf";
                            if (m.Value.EndsWith("/"))
                            {
                                str111 += m.Value.Substring(3, m.Value.Length - 4) + ".aspx";
                            }
                            else
                            {
                                str111 += m.Value.Substring(3, m.Value.Length - 7) + ".aspx";
                            }
                        }
                    }
                    else
                    {
                        if (str111.StartsWith("/wb_"))
                        {
                            str111 = "/wMall/Buyer/wf";
                            if (m.Value.EndsWith("/"))
                            {
                                str111 += m.Value.Substring(4, m.Value.Length - 5) + ".aspx";
                            }
                            else
                            {
                                str111 += m.Value.Substring(4, m.Value.Length - 8) + ".aspx";
                            }
                        }
                        else if (str111.StartsWith("/wp_"))
                        {
                            str111 = "/wMall/Public/wf";
                            if (m.Value.EndsWith("/"))
                            {
                                str111 += m.Value.Substring(4, m.Value.Length - 5) + ".aspx";
                            }
                            else
                            {
                                str111 += m.Value.Substring(4, m.Value.Length - 8) + ".aspx";
                            }
                        }
                        else if (str111.StartsWith("/ws_"))
                        {
                            str111 = "/wMall/Seller/wf";
                            if (m.Value.EndsWith("/"))
                            {
                                str111 += m.Value.Substring(4, m.Value.Length - 5) + ".aspx";
                            }
                            else
                            {
                                str111 += m.Value.Substring(4, m.Value.Length - 8) + ".aspx";
                            }
                        }
                        else if (str111.StartsWith("/cs_"))
                        {
                            str111 = "/CustomerSys/wf";
                            if (m.Value.EndsWith("/"))
                            {
                                str111 += m.Value.Substring(4, m.Value.Length - 5) + ".aspx";
                            }
                            else
                            {
                                str111 += m.Value.Substring(4, m.Value.Length - 8) + ".aspx";
                            }
                        }




                        else if (str111.StartsWith("/s_"))
                        {
                            str111 = "/Sys/wf";
                            if (m.Value.EndsWith("/"))
                            {
                                str111 += m.Value.Substring(3, m.Value.Length - 4) + ".aspx";
                            }
                            else
                            {
                                str111 += m.Value.Substring(3, m.Value.Length - 7) + ".aspx";
                            }
                        }
                        else if (str111.StartsWith("/c_"))
                        {
                            str111 = "/Custom/wf";
                            if (m.Value.EndsWith("/"))
                            {
                                str111 += m.Value.Substring(3, m.Value.Length - 4) + ".aspx";
                            }
                            else
                            {
                                str111 += m.Value.Substring(3, m.Value.Length - 7) + ".aspx";
                            }
                        }
                        else if (str111.StartsWith("/h_"))
                        {
                            str111 = "/ShpMana/wf";
                            if (m.Value.EndsWith("/"))
                            {
                                str111 += m.Value.Substring(3, m.Value.Length - 4) + ".aspx";
                            }
                            else
                            {
                                str111 += m.Value.Substring(3, m.Value.Length - 7) + ".aspx";
                            }
                        }
                        else if (str111.StartsWith("/d_"))
                        {
                            str111 = "/Dealer/wf";
                            if (m.Value.EndsWith("/"))
                            {
                                str111 += m.Value.Substring(3, m.Value.Length - 4) + ".aspx";
                            }
                            else
                            {
                                str111 += m.Value.Substring(3, m.Value.Length - 7) + ".aspx";
                            }
                        }
                    }




                    if (!string.IsNullOrEmpty(context.Request.QueryString.ToString()))
                    {
                        context.RewritePath(str111 + "?" + context.Request.QueryString.ToString());
                    }
                    else
                    {
                        context.RewritePath(str111);
                    }
                    //requestPath = str111 + requestPath.Substring(m.Length); 
                    //context.RewritePath(requestPath);
                }
            }
            //string requestPath = context.Request.Path.ToLower();
            ////SiteUrls是下面的一个类，这里大家可以重构下 
            //foreach (SiteUrls.URLRewrite url in SiteUrls.GetSiteUrls().Urls)
            //{
            //    //是否找到了匹配选项 
            //    if (Regex.IsMatch(requestPath, url.Pattern, RegexOptions.None | RegexOptions.IgnoreCase))
            //    {
            //        //开始替换成我们程序能读懂的url 
            //        string newUrl = Regex.Replace(requestPath.Substring(context.Request.Path.LastIndexOf("/")),
            //        url.Pattern, url.QueryString, RegexOptions.None | RegexOptions.IgnoreCase);
            //        //这里你可以输出一下看看 
            //        //context.Response.Write(url.Page + "<br>" + newUrl+"<br>"); 
            //        //开始把用户便于记忆的URL替换成程序能读懂的url 
            //        context.RewritePath(url.Page, string.Empty, newUrl);
            //    }
            //}
        }
    }

    public class SiteUrls
    {
        //定义成volatitle类型主要是为了多线程访问方便,在这个示例程序中没什么实际意义，项目大了就有用了 
        private static volatile SiteUrls instance = null;
        string UrlsFile = HttpContext.Current.Server.MapPath("/config/urls.config");
        //定义两个属性 
        private System.Collections.ArrayList _Urls;
        public System.Collections.ArrayList Urls
        {
            get { return _Urls; }
            set { _Urls = value; }
        }
        //这个就是个键植对 表害怕一点也不高深 
        private System.Collections.Specialized.NameValueCollection _Paths;
        public System.Collections.Specialized.NameValueCollection Paths
        {
            get { return _Paths; }
            set { _Paths = value; }
        }
        //构造函数 
        private SiteUrls()
        {
            Urls = new System.Collections.ArrayList();
            Paths = new System.Collections.Specialized.NameValueCollection();
            //以XML个数读取那CONFIG文件 
            XmlDocument urlconfig = new XmlDocument();
            urlconfig.Load(UrlsFile);
            XmlNode root = urlconfig.SelectSingleNode("urls");
            foreach (XmlNode n in root.ChildNodes)
            {
                //XmlNodeType.Comment如果不是注释 
                if (n.NodeType != XmlNodeType.Comment && n.Name.ToLower() == "rewrite")
                {
                    XmlAttribute name = n.Attributes["name"];
                    XmlAttribute path = n.Attributes["path"];
                    XmlAttribute page = n.Attributes["page"];
                    XmlAttribute querystring = n.Attributes["querystring"];
                    XmlAttribute pattern = n.Attributes["pattern"];

                    if (name != null && path != null && page != null
                    && querystring != null && pattern != null)
                    {
                        Paths.Add(name.Value, path.Value);
                        //压进去的都是url实体类 
                        Urls.Add(new URLRewrite(name.Value, pattern.Value, page.Value.Replace("^", "&"),
                        querystring.Value.Replace("^", "&")));
                    }
                }
            }
        }
        //用方法实例化 
        public static SiteUrls GetSiteUrls()
        {
            if (instance == null)
            {
                instance = new SiteUrls();
            }
            return instance;
        }

        #region url实体类
        public class URLRewrite
        {
            #region 成员变量
            private string _Name;
            public string Name
            {
                get { return _Name; }
                set { _Name = value; }
            }

            private string _Pattern;
            public string Pattern
            {
                get { return _Pattern; }
                set { _Pattern = value; }
            }

            private string _Page;
            public string Page
            {
                get { return _Page; }
                set { _Page = value; }
            }

            private string _QueryString;
            public string QueryString
            {
                get { return _QueryString; }
                set { _QueryString = value; }
            }
            #endregion
            #region 构造函数
            public URLRewrite(string name, string pattern, string page, string querystring)
            {
                _Name = name;
                _Pattern = pattern;
                _Page = page;
                _QueryString = querystring;
            }
            #endregion
        }
        #endregion
    }


}